import { NextResponse } from "next/server"
import {getItemBalance} from "@/server/database/repositories/itemOperation"
import {balanceParamZod,z} from "@/shared/formDataSchema"
import type { NextRequest } from 'next/server'
import { getServerUser } from "@/lib/session"
export async function GET( req: NextRequest) {
  try{
    const paramData = {
      happened_after:'',
      happened_before:'',
      group_by: '',
      kind:''
    }
    const params = req.nextUrl.searchParams
    paramData.happened_after = params.get('happened_after') ?? ''
    paramData.happened_before = params.get('happened_before') ?? ''
    balanceParamZod.parse(paramData)

    const user = await getServerUser() as User
    const {id: user_id} = user ?? {}
    const res = await getItemBalance(paramData, user_id)
    return NextResponse.json({resource:res})
  }
  catch(error){
    if (error instanceof z.ZodError) {
      const statusMessage = error.issues.map(issue => issue.message).join("; ");
      return NextResponse.json( statusMessage, { status: 400} )
    }
    return NextResponse.json( '服务器出错，概览数据获取失败！', { status: 500} )
  }
}